const hmac256 = require('crypto-js/hmac-sha256');
const CallbackService = require('../service/callback');
const { logger } = require('../utils');
// const path = require('path');
// const fs = require('fs');
// const jsonfile = require('jsonfile');
// const callbacklogsFile = path.join(__dirname, '../data/callback-log.json');
// const errorlogsFile = path.join(__dirname, '../data/error-log.json');

const callbackService = new CallbackService();

module.exports = (app) => {
  app.post(`${process.env.VUE_APP_BASE_API}/common/callback`, (req, res) => {
    const { body } = req;
    const contentSignature = res.headers?.['content-signature'] || res.headers?.['Content-Signature'] || '';
    // 验证secret-token
    const signature = `sha256=${hmac256(process.env.VUE_APP_CHANNEL_APP_TOKEN, body ? JSON.stringify(body) : '')}`;
    // let callbacklogs = [];

    // if (fs.existsSync(callbacklogsFile)) {
    //   callbacklogs = jsonfile.readFileSync(callbacklogsFile) || [];
    // }

    // callbacklogs.push({
    //   signature,
    //   contentSignature,
    //   body,
    // });

    logger.log({
      type: 'callback',
      signature,
      contentSignature,
      body,
    });

    // jsonfile.writeFileSync(callbacklogsFile, callbacklogs, { spaces: 2 });

    if (body.MsgType === 'OrgOpenTsignBiz') {
      callbackService.orgOpenTsignBiz(body.MsgData);
    } else if (body.MsgType === 'FlowStatusChange') {
      callbackService.updateSignStatusChange(body.MsgData);
    } else if (body.MsgType === 'VerifyStaffInfo') { // 员工加入企业
      callbackService.insertChannelOperator(body.MsgData);
    }

    res.status(200).json({
      message: 'ok',
    });
  });

  app.get(`${process.env.VUE_APP_BASE_API}/common/callbacklogs`, async (req, res) => {
    const callbacklogs = await logger.getLogs({
      type: 'callback',
    });

    res.status(200).json(callbacklogs);
  });
  // 错误日志
  app.get(`${process.env.VUE_APP_BASE_API}/common/errorlogs`, async (req, res) => {
    const errorlogs = await logger.getLogs({
      type: 'error',
    });
    res.status(200).json(errorlogs);
  });

  app.get(`${process.env.VUE_APP_BASE_API}/common/logs`, async (req, res) => {
    const { type } = req.query || {};
    const logs = await logger.getLogs({
      type,
    });
    res.status(200).json(logs);
  });

  app.post(`${process.env.VUE_APP_BASE_API}/common/clearlogs`, async (req, res) => {
    try {
      const result = await logger.clearLogs();
      res.status(200).json({
        code: 200,
        result,
      });
    } catch (err) {
      res.status(200).json({
        code: 200,
        message: err.message,
        stack: err.stack,
      });
    }
  });
};
